import pika

credentials = pika.PlainCredentials("admin", "admin")
connection = pika.BlockingConnection(pika.ConnectionParameters(
    host='172.16.1.120',
    port=5672,virtual_host='devHost',
    credentials=credentials))

channel = connection.channel()

# #  路由关键词
# routing_key_1 = ''

# 设置订阅模式
exchange_name = 'test_direct'
channel.exchange_declare(exchange=exchange_name,durable=True, exchange_type='direct')

# # 随机生成队列(并不会真的消费，只是会读出来数据)
# result = channel.queue_declare(queue='',durable=True)
# queue_name = result.method.queue

#指定队列(真的消费了数据)
result=channel.queue_declare(queue='test_queue',durable=True)
queue_name = result.method.queue


# 绑定 exchange 和 queue 绑定
channel.queue_bind(exchange=exchange_name,
                   queue=queue_name,
                   routing_key = 'test_queue')



# 定义一个回调函数来处理消息队列中的消息，这里是打印出来
def callback(ch, method, properties, body):
    ch.basic_ack(delivery_tag=method.delivery_tag)
    print(f"消费者接收到了任务: {body.decode()}")


# 闲置消费
channel.basic_qos(prefetch_count=1)

# 告诉rabbitmq，用callback来接收消息
channel.basic_consume(
    # queue='m1',
    queue=queue_name,
    auto_ack=False,
    on_message_callback=callback
)

# 开始接收信息，并进入阻塞状态，队列里有信息才会调用callback进行处理
channel.start_consuming()